<template>
  <div class="users-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>
    
    <!-- Search Form -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="激活" value="active"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- Table -->
    <el-card>
      <div slot="header" class="clearfix">
        <span>用户列表</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="120">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="role"
          label="角色">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === 'active' ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- Dialog for adding/editing users -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="用户" value="user"></el-option>
            <el-option label="访客" value="guest"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" placeholder="请选择状态">
            <el-option label="激活" value="active"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportDataToCsv } from '@/utils/export'

export default {
  name: 'Users',
  data() {
    return {
      loading: false,
      exportLoading: false,
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        username: '',
        status: ''
      },
      dialogVisible: false,
      dialogTitle: '新增用户',
      isEdit: false,
      userForm: {
        id: null,
        username: '',
        name: '',
        email: '',
        role: '',
        status: 'active'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchUsers()
  },
  methods: {
    // 获取用户列表
    fetchUsers() {
      this.loading = true
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据
        const mockUsers = []
        for (let i = 1; i <= 100; i++) {
          mockUsers.push({
            id: i,
            username: `user${i}`,
            name: `用户${i}`,
            email: `user${i}@example.com`,
            role: i % 3 === 0 ? 'admin' : (i % 3 === 1 ? 'user' : 'guest'),
            status: i % 5 === 0 ? 'disabled' : 'active'
          })
        }
        
        // 搜索过滤
        let filteredUsers = [...mockUsers]
        if (this.searchForm.username) {
          filteredUsers = filteredUsers.filter(user => user.username.includes(this.searchForm.username))
        }
        if (this.searchForm.status) {
          filteredUsers = filteredUsers.filter(user => user.status === this.searchForm.status)
        }
        
        // 分页
        this.total = filteredUsers.length
        const startIndex = (this.currentPage - 1) * this.pageSize
        this.userList = filteredUsers.slice(startIndex, startIndex + this.pageSize)
        
        this.loading = false
      }, 500)
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.fetchUsers()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm = {
        username: '',
        status: ''
      }
      this.handleSearch()
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchUsers()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchUsers()
    },
    
    // 添加用户
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增用户'
      this.userForm = {
        id: null,
        username: '',
        name: '',
        email: '',
        role: '',
        status: 'active'
      }
      this.dialogVisible = true
    },
    
    // 编辑用户
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑用户'
      this.userForm = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
    },
    
    // 删除用户
    handleDelete(row) {
      this.$confirm('确认删除该用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        this.userList = this.userList.filter(user => user.id !== row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 提交表单
    submitForm() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            // 编辑模式，找到并更新用户
            const index = this.userList.findIndex(user => user.id === this.userForm.id)
            if (index !== -1) {
              this.userList.splice(index, 1, this.userForm)
            }
            this.$message.success('编辑成功')
          } else {
            // 新增模式，生成ID并添加到列表
            const newUser = { ...this.userForm, id: Date.now() }
            this.userList.unshift(newUser)
            this.$message.success('添加成功')
          }
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },

    // 导出CSV
    async exportData() {
      this.exportLoading = true
      try {
        // 获取所有用户数据（模拟）
        const allData = this.userList || []
        
        const columns = [
          { prop: 'id', label: 'ID' },
          { prop: 'username', label: '用户名' },
          { prop: 'name', label: '姓名' },
          { prop: 'email', label: '邮箱' },
          { prop: 'role', label: '角色' },
          { prop: 'status', label: '状态', formatter: (row) => row.status === 'active' ? '激活' : '禁用' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `用户管理_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  }
}
</script>

<style scoped>
.users-container {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 